package org.example.servlet.stuinfo;

import com.google.gson.Gson;
import org.example.dao.StuinfoDao;
import org.example.entity.BaseResponse;
import org.example.entity.Stuinfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/index.stuinfo")
public class FindAllStuinfoServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理Get请求

        // 封装
        // dao ===> data access object ==> 对数据进行操作（查询、修改、删除）
        // ===> 解耦
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 设置返回的数据类型
        resp.setContentType("application/json");


        ArrayList<Stuinfo> stuinfo = StuinfoDao.findAllStuinfo();
        BaseResponse<ArrayList<Stuinfo>> baseResponse = new BaseResponse<>();
        baseResponse.setCode(0);
        baseResponse.setMsg("成功");
        baseResponse.setCount(stuinfo.size());
        baseResponse.setData(stuinfo);


        // Gson google json
        Gson gson = new Gson();
        // 将Java对象转化为Json字符串
        String json = gson.toJson(baseResponse);

        System.out.println(json);

        PrintWriter writer = resp.getWriter();
        writer.write(json);
        // 刷新页面
        writer.flush();

    }
}
